#include "raw_listener.h"
#include "../Errors/errors.h"
#include "../packet_headers/iphdr.h"
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <errno.h>
#include <string>

using namespace std;

RawListener::RawListener(const char * dev, int time) {
	string filter = "";
	duration = time;

	if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
		set_error_message((string("Can't get netmask for device ")+string(dev)).c_str());
		state = -1;
		net = 0;
		mask = 0;
	}
	handle = pcap_open_live(dev, BUFSIZ, 1, time, errbuf);
	if (handle == NULL) {
		set_error_message((string("Couldn't open device: ")+string(errbuf)).c_str());
		state = -1;
		return;
	}
	if (pcap_compile(handle, &fp, filter.c_str(), 0, net) == -1) {
		set_error_message("Couldn't parse filter");
		state = -1;
		return;
	}
	if (pcap_setfilter(handle, &fp) == -1) {
		set_error_message("Couldn't install filter");
		state = -1;
		return;
	}
	state = 0;
}

int RawListener::recv(char * _buf, unsigned int _sz) {
	struct pcap_pkthdr header;
	const u_char *packet;
	packet = pcap_next(handle, &header);
	memcpy(_buf, packet, min(_sz, header.len));
	return header.len;
}

int RawListener::finish() {
	pcap_close(handle);
	return 0;
}
